﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Configuration;

namespace CMLPDictHelper
{
    class DataBaseOperater
    {
        private SqlConnection _con;
        public SqlConnection Connection { get { return this._con; } }
        //DataBaseOperate dbo = new DataBaseOperate();

        private string _ip;
        private string _user;
        private string _password;
        private string _database;
        //数据库连接函数
        public DataBaseOperater(string ip, string uid, string pwd, string database)
        {
            this._con = new SqlConnection(String.Format(@"server={0};uid={1};pwd={2};database={3}", ip, uid, pwd, database));
            this._ip = ip;
            this._user = uid;
            this._password = pwd;
            this._database = database;
        }

        private void Open()
        {
            if (this._con.State != ConnectionState.Open)
            {
                try
                {
                    this._con.Open();
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    _con.Close();
                    throw e;
                }
            }
        }

        public DataTable Query(string sql)
        {
            Open();
            SqlCommand cmd = _con.CreateCommand();
            cmd.CommandText = sql;
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds, "Table");
            sda.Dispose();
            cmd.Dispose();
            Close();
            return ds.Tables["Table"];
        }

        private void Close()
        {
            if (this._con.State != ConnectionState.Closed)
            {
                this._con.Close();
            }
        }
    }
}
